import axios from 'axios';
import qs from 'qs'
import router from '../router'
var instance = axios.create();
instance.defaults.timeout = 15000;
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//token header
axios.interceptors.request.use(config => {
    config.headers['token'] = localStorage.getItem('token')
    return config
})

export default {
    /**
     * HTTP GET
     * @param url
     * @param params
     * @returns {Promise<unknown>}
     */
    fetchGet(url, params = {}) {
        return new Promise((resolve, reject) => {
            // if (localStorage.getItem('token')) {
            //     params.token = localStorage.getItem('token')
            // }
            axios.get(url, {params: params}).then(res => {
                if (res.data && res.data.success === true) {
                    resolve(res.data.data);
                } else {
                    if (res.data.msg === '无效TOKEN') {
                        router.push('/login')
                    } else {
                        reject(res.data.msg);
                    }
                }
            }).catch(error => {
                if (error.response && error.response.data.msg) reject(error.response.data.msg)
                else reject(error.message);
            })
        })
    },
    /**
     * HTTP POST
     * @param url
     * @param params
     * @returns {Promise<unknown>}
     */
    fetchPost(url, params = {}) {
        return new Promise((resolve, reject) => {
            // if (localStorage.getItem('token')) {
            //     params.token = localStorage.getItem('token')
            // }
            axios.post(url, qs.stringify(params)).then(res => {
                if (res.data && res.data.success === true) {
                    resolve(res.data.data);
                } else {
                    if (res.data.msg === '无效TOKEN') {
                        router.push('/login')
                    } else {
                        reject(res.data.msg);
                    }
                }
            }).catch(error => {
                if (error.response && error.response.data.msg) reject(error.response.data.msg)
                else reject(error.message);
            })
        })
    }
}

